<script setup>
import {ref, defineProps, onMounted} from "vue"
import {convertDate} from "@/utils/index.js";
import {useRouter} from "vue-router";
import {getRemind, createRemind, updateRemind} from "@/api/eyeCare.js";
import {showFailToast, showSuccessToast} from "vant";

const props = defineProps({
  patientId: String
})
const param = ref({
  remindTime: "",
  preRemindDay: null
})
const router = useRouter()
const showPicker = ref(false)
const pickerValue = ref(convertDate(new Date()));

const onPopup = () => {
  showPicker.value = true
};

const onConfirm = ({selectedValues}) => {
  pickerValue.value = selectedValues
  param.value.remindTime = selectedValues.join("-")
  showPicker.value = false
}

const onFailed = (errors) => {
  console.log(errors)
}

const handleSave = async () => {
  let data = {
    ...param.value,
    patientId: props.patientId
  }
  let resp = await createRemind(data)
  if (resp.code === 0) {
    showSuccessToast({type: 'success', message: '保存成功'});
    router.back()
  } else {
    showFailToast({type: 'danger', message: '保存失败'});
  }
}

onMounted(() => {
  getRemind(props.patientId).then(res => {
    if (res.data) {
      param.value = res.data
      pickerValue.value = convertDate(new Date(res.data.remindTime))
    } else {
      param.value = {
        remindTime: "",
        preRemindDay: 0
      }
    }
  })
})

</script>

<template>
  <van-cell-group inset>
    <van-form ref="formRef" @failed="onFailed">
      <van-field
          label-width="120px"
          label="下次检查时间"
          v-model="param.remindTime"
          name="birthday"
          placeholder="请输入下次检查时间"
          @click="onPopup"
          is-link
          readonly
          required
      />
      <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
        <van-date-picker
            :model-value="pickerValue"
            @confirm="onConfirm"
            @cancel="showPicker = false"
            :min-date="new Date(1990, 0, 1)"
            :max-date="new Date()"
        />
      </van-popup>
      <van-field label-width="120px"
                 required
                 v-model="param.preRemindDay"
                 name="preRemindDay"
                 label="提前申请天数"
                 type="number"
      />
    </van-form>
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button @click="handleSave" block type="primary" native-type="submit">
      提交
    </van-button>
  </div>
</template>

<style scoped lang="scss">
.van-cell-group {
  margin-top: 16px;
}
</style>